<?php

declare(strict_types=1);
/**
 * This file is part of habo_new_media.
 *
 * @link     https://www.berlen.cn/
 * @contact  tech@berlen.cn
 * @license  http://gitlab.rehou.cn/habo/habo_new_media/-/blob/master/README.md
 */
namespace app\command;

use app\enum\CommandEnum;
use app\enum\CommonEnum;
use app\enum\OceanEnum;
use app\model\ClientAccountModel;
use app\model\OeAwemeListModel;
use app\service\client\AccountService;
use app\service\ocean\AdvertiserService;
use think\console\Input;
use think\console\Output;
use think\facade\Cache;
use think\facade\Db;

class OeAwemeListWork extends BaseWork
{
    public const REDIS_TASK_KEY = CommandEnum::OE_TASK_LIST_KEY[2];

    public array $clientAccountInfo = [];

    protected function configure()
    {
        // 指令配置
        $this->setName('oe_aweme_list_work');
        // 设置参数
        $this->setDescription('拉取巨量抖音授权关系');

        // 设置参数
        $this->addArgument('advertiser_id', null, '账户id')
            ->setHelp('php think oe_aweme_list_work [advertiser_id]');
    }

    protected function execute(Input $input, Output $output)
    {
        set_time_limit(0);
        $output->writeln('=======巨量引擎-拉取巨量抖音授权关系开始' . date('Y-m-d H:i:s', time()) . '=======');
        //        $advertiserId = $input->getArgument('advertiser_id');
        $redisKey = self::REDIS_TASK_KEY;
        $redis = Cache::store('redis')->handler();
        $count = 0;
        while (true) {
            if ($count >= 100) {
                break;
            }
            $advertiserId = $redis->lPop($redisKey);
            if ($advertiserId) {
                // 请求接口
                $this->clientAccountInfo = $this->_getClientAccountInfo($advertiserId);
                $page = 0;
                while (true) {
                    $token = AccountService::getToken(CommonEnum::OE_MEDIA, $advertiserId);
                    if (! $token) {
                        break;
                    }
                    ++$page;
                    $result = $this->_getAppData($token, $advertiserId, $page);
                    if (! $result) {
                        $err = ['params' => ['token' => $token, 'advertiserId' => $advertiserId, 'page' => $page], 'response' => AdvertiserService::getError(0)];
                        $output->writeln('=======error:' . json_encode($err, JSON_UNESCAPED_UNICODE) . '=======' . PHP_EOL);
                        break;
                    }
                    $list = $result['data']['list'];
                    if (count($list) == 0) {
                        break;
                    }
                    foreach ($list as $v) {
                        $dataInfo = $this->_getAppInfo($advertiserId, $v['aweme_id']);
                        if (! empty($dataInfo)) {
                            $res = $this->_updateAdvertiserData($dataInfo['id'], $v);
                        } else {
                            $res = $this->_insertAdvertiserData($advertiserId, $v);
                        }
                        if (! $res) {
                            echo self::getError(0);
                        }
                    }
                }
                ++$count;
            } else {
                break;
            }
        }

        $output->writeln('=======巨量引擎-拉取巨量抖音授权关系结束' . date('Y-m-d H:i:s', time()) . '=======');
    }

    /**
     * @return bool|mixed|string
     */
    private function _getAppData(string $token = '', string $advertiserId = '', int $page = 1)
    {
        $headers = [
            'Access-Token' => $token,
            'Content-Type' => 'application/json',
        ];
        $params = [
            'advertiser_id' => $advertiserId,
            'page' => $page,
            'page_size' => OceanEnum::MAX_CUSTOM_MATERIAL_PAGE_SIZE,
        ];

        return AdvertiserService::getAwemeList($headers, $params);
    }

    /**
     * 判断是否需要更新.
     * @param array $oldData 旧数据
     * @param array $newData 新数据
     */
    private function _isDataUpdate(array $oldData = [], array $newData = []): bool
    {
        $one = $oldData['update_time'] == $newData['update_time'];
        $two = $oldData['reason'] == $newData['reason'];
        $thr = $oldData['status'] == $newData['status'];
        $fur = $oldData['version_name'] == $newData['version_name'];
        $fiv = $oldData['channel_id'] == $newData['channel_id'];
        $six = $oldData['download_url'] == $newData['download_url'];
        $sen = $oldData['remark'] == $newData['remark'];

        if ($one && $two && $thr && $fur && $fiv && $six && $sen) {
            return true;
        }

        return false;
    }

    /**
     * 获取信息.
     * @param string $advertiserId 账户id
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    private function _getAppInfo(string $advertiserId = '', string $awemeId = ''): array
    {
        $where = [
            ['aweme_id', '=', $awemeId],
            ['advertiser_id', '=', $advertiserId],
        ];

        $info = (new OeAwemeListModel())->where($where)->field(true)->find();
        if (! $info) {
            return [];
        }

        return $info->toArray();
    }

    /**
     * 修改信息.
     * @param int $id 主键ID
     * @param array $info 信息数据
     */
    private function _updateAdvertiserData(int $id = 0, array $info = []): bool
    {
        try {
            $data = [
                'auth_status' => $info['auth_status'],
                'auth_type' => $info['auth_type'],
                'aweme_id' => $info['aweme_id'],
                'aweme_name' => $info['aweme_name'],
                'end_time' => $info['end_time'],
                'start_time' => $info['start_time'],
                'sub_status' => $info['sub_status'] ? $info['sub_status'] : '',
                'video_info' => $info['video_info'] ? json_encode($info['video_info'], JSON_UNESCAPED_UNICODE) : [],
                'update_time' => time(),
            ];
            Db::startTrans();
            $one = (new OeAwemeListModel())->where('id', $id)->update($data);
            if ($one) {
                Db::commit();
                return true;
            }
            Db::rollback();
            return false;
        } catch (\Exception $e) {
            return self::setError($e->getMessage());
        }
    }

    /**
     * 插入广告报表信息.
     * @param string $advertiserId 账户ID
     * @param array $info 信息数据
     */
    private function _insertAdvertiserData(string $advertiserId = '', array $info = []): bool
    {
        try {
            Db::startTrans();
            $data = [
                'advertiser_id' => $advertiserId,
                'account_id' => $this->clientAccountInfo['id'],
                'auth_status' => $info['auth_status'],
                'auth_type' => $info['auth_type'],
                'aweme_id' => $info['aweme_id'],
                'aweme_name' => $info['aweme_name'],
                'end_time' => $info['end_time'],
                'start_time' => $info['start_time'],
                'sub_status' => $info['sub_status'] ? $info['sub_status'] : '',
                'video_info' => $info['video_info'] ? json_encode($info['video_info'], JSON_UNESCAPED_UNICODE) : [],
                'create_time' => time(),
            ];
            $insertId = (new OeAwemeListModel())->insertGetId($data);
            if ($insertId <= 0) {
                Db::rollback();
                return false;
            }
            Db::commit();
            return true;
        } catch (\Exception $e) {
            dump($e);
            return self::setError($e->getMessage());
        }
    }

    /**
     * 获取账户信息.
     * @param string $advertiserId 账户ID
     * @throws
     */
    private function _getClientAccountInfo(string $advertiserId = ''): array
    {
        $info = (new ClientAccountModel())->where('advertiser_id', $advertiserId)->field(true)->find();
        if (! $info) {
            return [];
        }
        return $info->toArray();
    }
}
